package cc.miwuya.owner.service.impl;

import cc.miwuya.common.util.JwtUtils;
import cc.miwuya.community.domain.Role;
import cc.miwuya.owner.client.RoleClient;
import cc.miwuya.owner.domain.User;
import cc.miwuya.owner.mapper.UserMapper;
import cc.miwuya.owner.service.UserService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 杩烽浘妫灄
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-02-22 20:13:04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    RoleClient roleClient;
    @Resource
    HttpServletRequest httpServletRequest;

    @Override
    public User getUserByUsername(String username) {
        User user = getOne(new QueryWrapper<User>().eq("username", username));
        return user;
    }

    @Override
    public Object getPage(Page page, String username) {
        Page<User> userPage = null;
        if (!StrUtil.isEmpty(username)) {
            userPage = page(page, new QueryWrapper<User>().like("username", username));
        } else {
            userPage = page(page, new QueryWrapper<User>());
        }
        return userPage;
    }

    @Override
    public Object getUserRole(Long id) {
        List<Role> userRole = roleClient.getUserRole(id);
        return userRole;
    }

    @Override
    public User getCurrentUser() {
        return getById(getCurrentUsrId());
    }

    @Override
    public Long getCurrentUsrId() {
        String authorization = httpServletRequest.getHeader("Authorization");
        Claims claim = JwtUtils.getClaimByToken(authorization, "community");
        JSON parse = JSONUtil.parse(claim);
        System.out.println(parse);
        Long username = Long.parseLong(parse.getByPath("userId").toString());
        return username;
    }
}